/*
 * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package com.albert.iotcar;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.albert.model.NetConfigModel;
import com.albert.pjsua2.MyBuddy;
import com.albert.pjsua2.SipManager;
import com.albert.pjsua2.SipManagerCallBack;
import com.albert.tool.NetConfigManager;

import org.pjsip.PjCameraInfo2;
import org.pjsip.pjsua2.BuddyConfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private ListView buddyListView;
    private SimpleAdapter buddyListAdapter;
    private int buddyListSelectedIdx = -1;
    ArrayList<Map<String, String>> buddyList;

    public String serverIp = "192.168.43.8";

    public String account = "";
    public String pass = "";
    public String otherAccount = "1004";
    public String sip = "";
    public int port = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().setTitle("");
        checkPermissions();
        CameraManager cm = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        PjCameraInfo2.SetCameraManager(cm);

        NetConfigManager.initWithServer("http://"+ serverIp + ":8400/userService/teacher/deviceGetServiceNetConfig", new NetConfigManager.InitCallback() {
            @Override
            public void onSuccess(NetConfigModel model) {
                accountSetting();
                dataSetting();
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    private void accountSetting() {
        account = NetConfigManager.getConfig().sipAccount;
        pass = NetConfigManager.getConfig().sipPass;
        sip = NetConfigManager.getConfig().sip;
        port = NetConfigManager.getConfig().sipPort;
        SipManager.getInstance().accountSetting(this, account, pass, sip, port, new SipManagerCallBack() {

            @Override
            public void finishCallBack() {
                finish();
            }

            @Override
            public void INCOMING_CALLCallBack(Boolean pickUp) {
                pushToCallActivity(pickUp);
            }

            @Override
            public void REG_STATECallBack(String msg_str) {
                TextView tvInfo = (TextView) findViewById(R.id.textViewInfo);
                tvInfo.setText("Last status: " + msg_str);
            }

            @Override
            public void BUDDY_STATECallBack(int idx, String status) {
                buddyList.get(idx).put("status", status);
                buddyListAdapter.notifyDataSetChanged();
            }
        });
    }

    public void deleteFriend(View view) {
        if (buddyListSelectedIdx == -1 || buddyList.stream().count() == 0) return;

        final HashMap<String, String> item = (HashMap<String, String>) buddyListView.getItemAtPosition(buddyListSelectedIdx);
        String buddy_uri = item.get("uri");

        DialogInterface.OnClickListener ocl = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        SipManager.getInstance().account.delBuddy(buddyListSelectedIdx);
                        buddyList.remove(item);
                        buddyListAdapter.notifyDataSetChanged();
                        buddyListSelectedIdx = -1;
                        break;
                    case DialogInterface.BUTTON_NEGATIVE:
                        break;
                }
            }
        };

        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setTitle(buddy_uri);
        adb.setMessage("\nDelete this buddy?\n");
        adb.setPositiveButton("Yes", ocl);
        adb.setNegativeButton("No", ocl);
        adb.show();
    }

    public void testAction(View view) {
        pushToCallActivity(false);
    }

    public void dataSetting() {

        buddyList = new ArrayList<Map<String, String>>();
        for (int i = 0; i < SipManager.getInstance().account.buddyList.size(); i++) {
            buddyList.add(putData(SipManager.getInstance().account.buddyList.get(i).cfg.getUri(), SipManager.getInstance().account.buddyList.get(i).getStatusText()));
        }

        String[] from = {"uri", "status"};
        int[] to = {android.R.id.text1, android.R.id.text2};
        buddyListAdapter = new SimpleAdapter(this, buddyList, android.R.layout.simple_list_item_2, from, to);

        buddyListView = (ListView) findViewById(R.id.listViewBuddy);

        buddyListView.setAdapter(buddyListAdapter);
        buddyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
                view.setSelected(true);
                buddyListSelectedIdx = position;
            }
        });
    }

    private HashMap<String, String> putData(String uri, String status) {
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("uri", uri);
        item.put("status", status);
        return item;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) { // 顶部操作按钮
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        addEditFriend(null);
        return true;
    }

    //添加电话簿
    private void addEditFriend(BuddyConfig initial) {
        final BuddyConfig cfg = new BuddyConfig();
        final BuddyConfig old_cfg = initial;
        final boolean is_add = initial == null;

        LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.dlg_add_buddy, null);

        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        adb.setView(view);

        final EditText etUri = (EditText) view.findViewById(R.id.editTextUri);
        final CheckBox cbSubs = (CheckBox) view.findViewById(R.id.checkBoxSubscribe);
        cbSubs.setChecked(true);

        etUri.setText("sip:" + otherAccount + "@" + sip);
        if (is_add) {
            adb.setTitle("Add Friend");
        } else {
            adb.setTitle("Edit Friend");
            etUri.setText(initial.getUri());
            cbSubs.setChecked(initial.getSubscribe());
        }

        adb.setCancelable(false);
        adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                cfg.setUri(etUri.getText().toString());
                cfg.setSubscribe(cbSubs.isChecked());

                if (is_add) {
                    SipManager.getInstance().account.addBuddy(cfg);
                    buddyList.add(putData(cfg.getUri(), ""));
                    buddyListAdapter.notifyDataSetChanged();
                    buddyListSelectedIdx = -1;
                } else {
                    if (!old_cfg.getUri().equals(cfg.getUri())) {
                        SipManager.getInstance().account.delBuddy(buddyListSelectedIdx);
                        SipManager.getInstance().account.addBuddy(cfg);
                        buddyList.remove(buddyListSelectedIdx);
                        buddyList.add(putData(cfg.getUri(), ""));
                        buddyListAdapter.notifyDataSetChanged();
                        buddyListSelectedIdx = -1;
                    } else if (old_cfg.getSubscribe() != cfg.getSubscribe()) {
                        MyBuddy bud = SipManager.getInstance().account.buddyList.get(buddyListSelectedIdx);
                        try {
                            bud.subscribePresence(cfg.getSubscribe());
                        } catch (Exception e) {
                        }
                    }
                }
            }
        });
        adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog ad = adb.create();
        ad.show();
    }

    //拨打电话
    public void makeCall(View view) {
        if (buddyListSelectedIdx == -1) return;

        HashMap<String, String> item = (HashMap<String, String>) buddyListView.getItemAtPosition(buddyListSelectedIdx);
        String buddy_uri = item.get("uri");
        SipManager.getInstance().makeCall(buddy_uri, new SipManagerCallBack() {
            @Override
            public void INCOMING_CALLCallBack(Boolean pickUp) {
                pushToCallActivity(false);
            }
        });
    }

    private void pushToCallActivity(Boolean pickUpCall) {

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Intent intent = new Intent(this, CallActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("pickUpCall", pickUpCall);
            startActivity(intent);
        }, 100);
    }

    private void checkPermissions() {
        String permissions[] = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_NETWORK_STATE};
        ActivityCompat.requestPermissions(MainActivity.this, permissions, 0);
    }
}
